package com.liang.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.liang.mall.entity.Role;
import com.liang.mall.util.ResultEntity;
import com.liang.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liang
 * @since 2021-05-12
 */
@RestController
public class RoleController {

    @Autowired
    RoleService roleService;


    @GetMapping("/role/list")
    public ResultEntity<IPage> list(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10")Integer pageSize, @RequestParam(defaultValue = "") String roleName){

     IPage<Role> roleIPage =  roleService.getRoles(pageNum,pageSize,roleName);

     return ResultEntity.ok(roleIPage);

    }

    @DeleteMapping("/role/{id}")
    public ResultEntity delete(@PathVariable("id") Integer id){

      boolean success =   roleService.removeRoleById(id);

        if (success) {
            return ResultEntity.ok();
        }else {

            return ResultEntity.error("删除失败!");

        }



    }


//    @GetMapping("/role/{id}")
//    public ResultEntity getRole_resource(@PathVariable("id") Integer id){
//
//        Role role = roleService.getById(id);
//
//
//
//
//    }

    @PostMapping("/role/add")
    public ResultEntity roleAdd(@RequestBody Map map ){

//        ArrayList<Integer> menuIdList,@RequestBody String remark,@RequestBody String roleName
        ArrayList<Integer> menuIdList = (ArrayList<Integer>) map.get("menuIdList");
        String remark = (String) map.get("remark");

        String roleName = (String) map.get("roleName");

        Role role = new Role();

        role.setRoleName(roleName);
        role.setRemark(remark);

        roleService.save(role);

        Role role1 = roleService.getOne(new QueryWrapper<Role>().eq("role_name", roleName));

        Integer id = role1.getRoleId();


        roleService.addRoleResource(id,menuIdList);

        return ResultEntity.ok();

    }

}

